package cpasl;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

//import MPEG1.PictureBuffer;
//import MPEG1.VideoListener;
//import MPEG1.VideoViewer;

/**
 * Has an X in a circle drawn at a random location.
 * The user clicking on the X causes it to 
 * be drawn at a different random location.
 * http://marketplace.eclipse.org/marketplace-client-intro?mpc_install=1139
 * @author Sean Megeath
 */
public class CpaslPanel extends JPanel {

	private static final SimpleDateFormat FILE_NAME_FORMAT = new SimpleDateFormat("MM_DD_yyyy_hh_mm_ss");

	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("EEE MMM dd yy hh:mm:ss.SSS");
	private static final long DISPLAY_TO_BLANK_DELAY = 1000;
	private static final long BLANK_TO_CHOICE_DELAY = 500;
	private static final long BLANK_TO_DISPLAY_DELAY = 1500;
	private static final String READY = "READY";
	private static final String CHOICE = "CHOICE";
	private static final String BLANK = "BLANK";
	private static final String DISPLAY = "DISPLAY";

	private static final int NUMBER_OF_BUTTONS = 11;
	
	private static final Color BACKGROUND = new Color(131, 131, 131);

	private long _lastDisplayTime;

	/** The x-value of the X-circle's center. */
	private Integer _centerX = 0;

	/** The y-value of the X-circle's center. */
	private Integer _centerY = 0;

	/** Used to generate random numbers. */
	private Random _random = new Random(Calendar.getInstance().getTimeInMillis());

	private BufferedWriter _outputFileWriter = null;

	private int _clickCount = 1;

	private CardLayout cardLayout = new CardLayout();
	
	private CpaslPanel cpaslPanel = this;
	
	private ArrayList<ImageIcon> _imageIcons = new ArrayList<ImageIcon>();
	
//	private ArrayList<VideoViewer> _videoViewers = new ArrayList<VideoViewer>();
	
	/** The index in the list of video viewers of the last displayed video. */
	private int _viewerIndex = 0;
	
	private JFrame frame = null;
	
	private Timer _timer = new Timer();
	
	private ImageChoicePanel imageChoicePanel = null;
	
	private VideoDisplayPanel videoDisplayPanel = null; //TODO
	
	private int participantNumber = -1;
	

	/**
	 * Constructor 
	 * 
	 * @param participantNumber the number assigned to the person using the application
	 * @param width the width of the panel in pixels
	 * @param height the height of the panel in pixels
	 * @param frame a reference to the frame this panel is in
	 */
	public CpaslPanel(int participantNumber, int width, int height, JFrame frame,
			File videoDirectory, File imagesDirectory, File outputDirectory, int fileCount) {
//		this.participantNumber = participantNumber;
//		setSize(width, height);
//		setLayout(cardLayout);
//		this.frame = frame;
//		
//		CpaslVideoListener cpaslVideoListener = new CpaslVideoListener();
//		

//
//		ReadyPanel readyPanel = new ReadyPanel(width, height);
//		add(readyPanel, READY);
//		BlankPanel blankPanel = new BlankPanel(width, height);
//		add(blankPanel, BLANK);
//		imageChoicePanel = new ImageChoicePanel(width, height);
//		add(imageChoicePanel, CHOICE);
//		videoDisplayPanel = new VideoDisplayPanel(width, height);
//		videoDisplayPanel.setViewer(_videoViewers.get(_viewerIndex));
//		add(videoDisplayPanel, DISPLAY);
//		
//		String outputFilePath = outputDirectory.getAbsolutePath() + "/Cpasl_" + FILE_NAME_FORMAT.format(new Date()) + ".txt";
//		try {
//			_outputFileWriter = new BufferedWriter(new FileWriter(outputFilePath));
//			_outputFileWriter.write("Subject,Trial,Display,Response,Reaction Time (ms)");
//			_outputFileWriter.newLine();
//			_outputFileWriter.flush();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}

	public void closeFile() {
		try {
			_outputFileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private class BlankPanel extends JPanel {
		
		public BlankPanel(int width, int height) {
			setSize(width, height);
			setBackground(BACKGROUND);
		}
		
	}
	
	private void blankToDisplay() {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				cardLayout.show(cpaslPanel, DISPLAY);
				Date displayDate = new Date();
				_lastDisplayTime = displayDate.getTime();
//				videoDisplayPanel.getViewer().start();
			}

		});
//		_timer.schedule(new TimerTask() {
//
//			@Override
//			public void run() {
//				imageToBlank();
//			}
//			
//		}, DISPLAY_TO_BLANK_DELAY);
	
		
	}
	
	private void choiceToBlank() {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				cardLayout.show(cpaslPanel, BLANK);
			}

		});
		_timer.schedule(new TimerTask() {

			@Override
			public void run() {
				blankToDisplay();
			}
			
		}, BLANK_TO_DISPLAY_DELAY);
	}
	
	private void imageToBlank() {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				cardLayout.show(cpaslPanel, BLANK);
			}

		});
		_timer.schedule(new TimerTask() {

			@Override
			public void run() {
				SwingUtilities.invokeLater(new Runnable() {

					@Override
					public void run() {
						cardLayout.show(cpaslPanel, CHOICE);
					}

				});
			}
			
		}, BLANK_TO_CHOICE_DELAY - _random.nextInt(50));
	}
	
	private void initialImageDisplay() {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				cardLayout.show(cpaslPanel, DISPLAY);
				Date displayDate = new Date();
				_lastDisplayTime = displayDate.getTime();
			}

		});
		_timer.schedule(new TimerTask() {

			@Override
			public void run() {
				imageToBlank();
			}
			
		}, DISPLAY_TO_BLANK_DELAY);
	
		
	}

	private class ReadyPanel extends JPanel {

		public ReadyPanel(int width, int height) {
			setSize(width, height);
			setLayout(null);
			setBackground(BACKGROUND);
			JButton readyButton = new JButton("Ready?");
			readyButton.setSize(100, 30);
			int x = (width / 2) - (readyButton.getWidth() / 2);
			int y = (height / 2) - (readyButton.getHeight() / 2);
			readyButton.setLocation(x, y);
			readyButton.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					initialImageDisplay();
				}

			});
			add(readyButton, BorderLayout.CENTER);
		}

	}



	private class ImageChoicePanel extends JPanel {

		private ArrayList<JButton> _buttons = new ArrayList<JButton>();

		public ImageChoicePanel(int width, int height) {
			setSize(width, height);
			setLayout(null);
			setBackground(BACKGROUND);
			int buttonWidth = width / NUMBER_OF_BUTTONS;
			int buttonHeight = buttonWidth;
			int x = 0;
			int y = (height / 2) - (buttonHeight / 2);
			for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {
				JButton imageButton = new JButton(_imageIcons.get(i));
				imageButton.setName(String.valueOf(i));
				imageButton.addActionListener(new ColorChoiceActionListener());
				imageButton.setBorder(BorderFactory.createLineBorder(BACKGROUND, 5, false));
				imageButton.setBackground(BACKGROUND);
				imageButton.setBounds(x, y, buttonWidth, buttonHeight);
				add(imageButton);
				_buttons.add(imageButton);
				x += buttonWidth;
			}
		}
		
		private class ColorChoiceActionListener implements ActionListener {

			@Override
			public void actionPerformed(ActionEvent e) {
				Date clickDate = new Date();
				long clickTime = clickDate.getTime();
				String update = participantNumber + "," + _clickCount + "," + _viewerIndex + "," + ((JButton) e.getSource()).getName() + "," + (clickTime - _lastDisplayTime);
				try {
					_outputFileWriter.write(update);
					_outputFileWriter.newLine();
					_outputFileWriter.flush();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			
				_viewerIndex = _random.nextInt(NUMBER_OF_BUTTONS);
//				videoDisplayPanel.setViewer(_videoViewers.get(_viewerIndex));
				choiceToBlank();
				
				_clickCount++;
				if (_clickCount == 50) {
					System.exit(0);
				}
			}
			
		}

	}

	private class VideoDisplayPanel extends JPanel {

		private static final int MARGIN = 10;

//		private VideoViewer _viewer = null;

		private int _x = 0;

		private int _y = 0;

		/** Used to generate random numbers. */
		private Random _random = new Random(Calendar.getInstance().getTimeInMillis());

		public VideoDisplayPanel(int width, int height) {
			setLayout(null);
			setBackground(Color.CYAN); //TODO BACKGROUND);
			setSize(width, height);
		}

//		public void setViewer(VideoViewer viewer) {
//			removeAll();
//			_viewer = viewer;
//			int newX = MARGIN + _random.nextInt(getWidth() - ((2 * MARGIN) + _viewer.getWidth()));
//			int newY = MARGIN + _random.nextInt(getHeight() - ((2 * MARGIN) + _viewer.getHeight()));
//			while (Point.distance(newX, newY, _x, _y) < _viewer.getWidth()) {
//				newX = MARGIN + _random.nextInt(getWidth() - ((2 * MARGIN) + _viewer.getWidth()));
//				newY = MARGIN + _random.nextInt(getHeight() - ((2 * MARGIN) + _viewer.getHeight()));
//			}
//			_x = newX;
//			_y = newY;
//			_viewer.setLocation(_x, _y);
//			add(_viewer);
		}
		
//		public VideoViewer getViewer() {
//			return _viewer;
//		}

//	}
	
//	private class CpaslVideoListener implements VideoListener {
//
//		@Override
//		public void pictureChanging(VideoViewer arg0, PictureBuffer arg1) {
//		}
//
//		@Override
//		public void videoStarted(VideoViewer arg0) {
//		}
//
//		@Override
//		public void videoStopped(VideoViewer arg0) {
//			imageToBlank();
//		}
//		
//	}

}
